from PyQt5 import QtWidgets,QtGui,QtCore
from RecordDeleteUI import Ui_RecordDelete
import sys
import sqlite3
import time
import datetime

class SalaryRecordDelete(QtWidgets.QWidget,Ui_RecordDelete):
    def __init__(self,username='test',dbpath='test.db'):
        super(SalaryRecordDelete,self).__init__()
        self.setupUi(self)
        self.setuptableView()
        
        self.username = username
        self.dbpath = dbpath
        self.setname()
        self.setdate()

        self.Delete_pushButton.clicked.connect(self.Delete)

    def setname(self):
        self.name_label.setText(self.username)
    def setdate(self):
        #init date
        self.Date_dateEdit.setDate(datetime.date.today())
    
    def setuptableView(self):
        self.model = QtGui.QStandardItemModel(self.tableView)
        self.model.setRowCount(0)
        self.model.setColumnCount(4)
        self.model.setHorizontalHeaderLabels(['Date','Name','Salary','RecordTime'])
        self.tableView.horizontalHeader().setStretchLastSection(True)
        self.tableView.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        self.tableView.setModel(self.model)

    def Delete(self):
        date = self.Date_dateEdit.text()
        name = self.username
        
        

        conn = sqlite3.connect(self.dbpath)
        c = conn.cursor()
        try:
            c.execute("DELETE FROM  record WHERE date=? AND name=?",\
                      (date,name))
            conn.commit()
        except sqlite3.IntegrityError :
            QtWidgets.QMessageBox.information(self,'Reminding:',"Check your date information!")
                
        #show the record info
        self.model.setRowCount(0) #init model
        c.execute("SELECT * FROM record WHERE name=?",[name])
        sqlquery = c.fetchall()
        for data in sqlquery:
            self.model.appendRow([QtGui.QStandardItem(data[0]), #date
                                  QtGui.QStandardItem(data[1]), #name
                                  QtGui.QStandardItem(str(data[2])), #salary
                                  QtGui.QStandardItem(data[3])  #recordtime
                                  ])
        c.close()
        conn.close()
        return
    
if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    salaryrecord = SalaryRecordDelete(username='test',dbpath='test.db')
    salaryrecord.show()
    sys.exit(app.exec())
